package top.carrotguo.weibo.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.refreshview.CustomRefreshView;
import com.sina.weibo.sdk.auth.AccessTokenKeeper;

import java.util.ArrayList;
import java.util.logging.Logger;

import butterknife.BindView;
import butterknife.ButterKnife;
import top.carrotguo.weibo.R;
import top.carrotguo.weibo.adapter.StatusAdapter;
import top.carrotguo.weibo.bean.HomeTimeLine;
import top.carrotguo.weibo.bean.UserInfo;
import top.carrotguo.weibo.contract.HomeContract;
import top.carrotguo.weibo.presenter.HomePresenter;
import top.carrotguo.weibo.retrofit.callback.ErrorInfo;
import top.carrotguo.weibo.ui.base.BaseActivity;
import top.carrotguo.weibo.ui.base.MVPBaseFragment;
import top.carrotguo.weibo.utils.TitlebarBuilder;
import top.carrotguo.weibo.utils.ToastUtils;
import top.carrotguo.weibo.utils.UIUtils;
import top.carrotguo.weibo.widget.RecycleViewDivider;

public class HomeFragment extends MVPBaseFragment<HomeContract.View,HomePresenter>
    implements HomeContract.View{

    @BindView(R.id.rv_status)
    CustomRefreshView rvStatus;
    private ArrayList<HomeTimeLine.UsersBean> datas = new ArrayList<>();

    /*当前在第几页*/
    private int mCurPage = 1;
    /*每一页拥有的数据的数量*/
    private int mPageSize = 10;
    private StatusAdapter adapter;
    public static final int LOAD_FIRST = 1;
    public static final int LOAD_MORE = 2;
    public static final int LOAD_REFRESH = 3;

    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter();
    }

    @Override
    protected void getBundleExtras(Bundle bundle) {

    }

    @Override
    protected View initContentView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home,container,false);
    }

    @Override
    protected void initLogic() {
        ButterKnife.bind(this,mRootView);
        initTitle();
        initList();

        //第一次进入先获取第一页的数据
        mPresenter.getTimeline(AccessTokenKeeper.readAccessToken(mContext),mPageSize,mCurPage,LOAD_FIRST);
        //获取用户数据
        mPresenter.getUserInfo(AccessTokenKeeper.readAccessToken(mContext));
    }

    private void initList(){
        adapter = new StatusAdapter(mContext,datas);
        rvStatus.setAdapter(adapter);
        //给rv的每一项设置点击监听
        adapter.setItemClickListener(new StatusAdapter.ItemClickListener() {
            @Override
            public void click(int position) {
                //将被点击的item的微博数据传输给详情页
                BaseActivity activity = (BaseActivity) mContext;
                Bundle bundle = new Bundle();
                bundle.putSerializable(HomeDetailActivity.BLOG_DATA,datas.get(position));
                activity.readyGo(HomeDetailActivity.class,bundle);
            }
        });
        adapter.setControllClickListener(new StatusAdapter.ControllClickListener() {
            @Override
            public void clickLike(int position) {
                showToast("点赞："+position);
            }

            @Override
            public void clickComment(int position) {
                showToast("评论"+position);
            }

            @Override
            public void clickRetweet(int position) {
                showToast("转发"+position);
            }
        });
        //设置progressbar颜色
        rvStatus.getSwipeRefreshLayout().setColorSchemeColors(getResources().getColor(R.color.orange));
        //设置分割线
        rvStatus.getRecyclerView().removeItemDecoration(new RecycleViewDivider(
                mContext,
                LinearLayoutManager.VERTICAL,
                UIUtils.dip2px(20),
                getResources().getColor(R.color.orange)));
        //初始化CustomRefreshView
        rvStatus.setOnLoadListener(new CustomRefreshView.OnLoadListener() {
            @Override
            public void onRefresh() {
                //下拉刷新
                mPresenter.getTimeline(AccessTokenKeeper.readAccessToken(mContext),mPageSize,mCurPage,LOAD_REFRESH);
            }

            @Override
            public void onLoadMore() {
                //上拉加载更多
                mPresenter.getTimeline(AccessTokenKeeper.readAccessToken(mContext),mPageSize,mCurPage,LOAD_MORE);
            }
        });

    }

    private void initTitle(){
        new TitlebarBuilder(mContext).setCenterTitle("首页")
                .setLeftText("左边")
                .setRightIcon(R.drawable.icon_person)
                .setLeftTextClick(new View.OnClickListener(){
                                 @Override
                                 public void onClick(View v) {
                                     showToast("左边");
                                 }
                             }
                )
                .setRightIconClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showToast("右边");
                    }
                });
    }

    @Override
    public void showLoadmoreSuccess(HomeTimeLine successInfo) {
        showToast("加载更多数据成功");
        if (successInfo != null && successInfo.getStatuses() != null && successInfo.getStatuses().size()>0) {
            //有更多数据
            datas.addAll(successInfo.getStatuses());
        } else {
            //加载到底了
            rvStatus.onNoMore();
        }
        //已经加载更多完成  停止加载更多
        rvStatus.stopLoadingMore();
        adapter.notifyDataSetChanged();
        //当前已经加载到下一页，所以页数+1
        mCurPage++;
    }

    @Override
    public void showLoadmoreFail(ErrorInfo errorInfo) {
        showToast("请求首页最近信息失败");
        rvStatus.onError();
    }

    @Override
    public void showRefreshSuccess(HomeTimeLine successInfo) {
        if (successInfo.getStatuses()!= null) {
            //先清除之前的数据，重新加载数据进来
            datas.clear();
            datas.addAll(successInfo.getStatuses());
        }
        rvStatus.complete();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void showRefreshFail(ErrorInfo errorInfo) {
        //弹出错误信息
        showToast(errorInfo.getErrorMsg());
        //停止刷新
        rvStatus.complete();
    }

    @Override
    public void showFirstLoadSuccess(HomeTimeLine successInfo) {

        //第一次加载数据成功
        if (successInfo.getStatuses()!=null && successInfo.getStatuses().size()>0) {
            //有加载到数据
            datas.addAll(successInfo.getStatuses());
        } else {
            //没有数据
            rvStatus.setEmptyView("暂无数据");
        }
        adapter.notifyDataSetChanged();
        mCurPage++;
    }

    @Override
    public void showFirstLoadFail(ErrorInfo errorInfo) {
        //第一次加载数据失败，显示失败页面
        rvStatus.setErrorView();
        adapter.notifyDataSetChanged();
    }

    /**
     * 获取用户详情
     * @param successInfo
     */
    @Override
    public void getUserInfoSuccessed(UserInfo successInfo) {
        ((BaseActivity)mContext).user = successInfo;
    }
}
